/*
 * @Author: wangyifei 844650674@qq.com
 * @Date: 2022-11-27 10:22:27
 * @LastEditors: wangyifei 844650674@qq.com
 * @LastEditTime: 2022-11-27 12:52:42
 * @FilePath: \management_system_template\admin-server\validator\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const validator = require("../middleware/validator");
const { User } = require("../model");
const { body } = require("express-validator");
const md5 = require("../util/md5");

exports.register = validator([
  // 配置验证规则
  body('account')
    .notEmpty()
    .withMessage('账号不能为空')
    .bail()
    .custom(async account => {
      const user = await User.findOne({
        account
      });
      if (user) {
        return Promise.reject('账号已存在');
      }
    }),
  body('password')
    .notEmpty()
    .withMessage("密码不能为空")
]);

exports.login = [
  validator([
    // 配置验证规则
    body("account")
      .notEmpty()
      .withMessage("用户名不能为空"),
    body("password")
      .notEmpty()
      .withMessage("密码不能为空")
  ]),
  validator([
    // 配置验证规则
    body("account").custom(async (account, { req }) => {
      const user = await User.findOne({
        account
      });
      if (!user) {
        return Promise.reject("账号不存在");
      }
      req.user = user;
    })
  ]),
  validator([
    // 配置验证规则
    body("password").custom(async (password, { req }) => {
      if (req.user.password === password) {
      } else {
        return Promise.reject("密码错误");
      }
    })
  ])
];

exports.updateUser = [
  validator([
    validator.isValidObjectId(['params'], 'id')
  ]), 
  async (req, res, next) => {
    const id = req.params.id
    const article = await Article.findById(id)
    req.article = article
    if (!article) {
      return res.status(404).end()
    }
    next()
  },
  async (req, res, next) => {
    if (req.user._id.toString() !== req.article.author.toString()) {
      return res.status(403).end()
    }
    next()
  }
];  
